import store from '@/store';
import axios from 'axios';
import { ElMessage  } from 'element-plus'
import Router from '@/router/index';
import {serialize} from "@/utils/serialize"

import qs from 'qs'
// 创建一个axios实例
const service = axios.create({
  baseURL: '/api', //import.meta.env.VITE_APP_BASE_API
  withCredentials: false,
  timeout: 600*1000,
  //是否返回其它状态码
  validateStatus:function(status){
    return status >= 200 && status <= 500
  }
});

// 请求拦截器
service.interceptors.request.use(
  config=>{
    let token = '';
    try {
        token = store.getters.token
      } catch(error)
      {
        console.error(error)
      }
    if (token) {
        config.headers['jwt-token'] = `${token}`;
      }
    // config.baseURL = config.headers['url'] ? config.headers['url'] : config.baseURL;

    // 获取token接口取消验证
    if(config.url.indexOf('/auth/oauth/token')>=0){
        config.headers.isToken = false;
        config.headers.Authorization = "Basic cGlnOnBpZw==";
      }
    // headers中配置serialize为true开启序列化
    if (config.method === 'post' && config.headers.serialize) {
      config.data = serialize(config.data)
      delete config.data.serialize
    }

    if (config.method === 'get') {
      config.paramsSerializer = function (params) {
        return qs.stringify(params, {arrayFormat: 'repeat'})
      }
    }
    //导出
    if(config.type == 'download'){
      config.headers.responseType = 'arraybuffer'
    }
      return config
    },
    error => {
        return Promise.reject(error);
    }
)

// 响应拦截器
service.interceptors.response.use( response=>{
    const res = response.data;
    // let status = response.status
    let status = res.code
    //用户信息失效，重定向登录页
    if (status === 401 || status === 403) {
      if(res.msg.indexOf('请登录') == -1){
        ElMessage({
          message: res.msg,
          type: 'error'
        })
      }
      // 清空全部缓存 重定向到登录页
      window.localStorage.clear()
      window.sessionStorage.clear()
      Router.push({path:'/login'})
      return
    }
    if(status === 101){
      ElMessage({
        message: res.msg,
        type: 'error'
      })
    }
    if(status === 426){
        ElMessage({
            message: '用户名不存在或密码错误',
            type: 'error'
        })
    }
    //返回错误
    if(status !== 200 && status !== 426  && status !== 1000){
        // ElMessage({
        //     message: response.data.msg,
        //     type: 'error'
        // })
        // return Promise.reject(new Error(response.data.msg))
    }
    return res
  },
  error=>{
    // ElMessage({
    //   message: error.message,
    //   type: 'error',
    //   duration: 5 * 1000
    // });
    return Promise.reject(error);
  }
)

export default service;
